/*
 * File Name：ChooseAreaWheel.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： ChooseAreaWheel.java
 * Modify By：RES-KUNZHU
 * Modify Date：2013-12-20
 * Modify Type：Add
 */
package com.ciwong.epaper.widget.wheel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.ciwong.epaper.R;
import com.ciwong.epaper.bean.City;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.utils.Utils;
import com.ciwong.epaper.widget.wheel.adapter.CityChooseAdapter;
import com.ciwong.epaper.widget.wheel.i.OnWheelViewChangedListener;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.widget.CWDialog;

import android.content.Context;
import android.content.res.Configuration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

/**
 * 地址选择器滚筒控件
 *
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2013-12-20
 * @since ciwong v.1.0
 */
public class WheelChooser extends CWDialog implements OnClickListener {
    private final int screenDpi450 = 450;

    private final int screenDpi300 = 300;

    private final int screenDpi150 = 150;

    private final int defalutSize = 22;

    private int defaultTextSize = defalutSize;

    private final int size45 = 45;

    private final int size30 = 30;

    private final int size10 = 10;

    private final int length = 7;

    /**
     * 刷新市标识
     */
    private final int refreshLevel = 2;

    private Context mContext;

    /**
     * 省
     */
    private WheelChooserView mProvinceWV;

    /**
     * 市
     */
    private WheelChooserView mCityWV;

    /**
     * 区
     */
    private WheelChooserView mTownWV;

    private List<City> mProvinceList = new ArrayList<City>();

    private List<City> mCityList = new ArrayList<City>();

    private List<City> mTownList = new ArrayList<City>();

    private City mCurProvince;

    private City mCurCity;

    private City mCurTown;

    private CityChooseAdapter mProvinceAdapter;

    private CityChooseAdapter mCityAdapter;

    private CityChooseAdapter mTownAdapter;

    private File mFile;

    /**
     * 选择返回给客户端实体，用于获取已选择的地区码，同步到服务器
     */
    private City mChooseCity;

    /**
     * 客户端显示的地区字符
     */
    private String chooseCityStr;

    private int mCityIndex;

    private int mProvinceIndex;

    private int mTownIndex;

    private ChooseCityCallback mCallback;

    /**
     * 菜单
     */
    private LinearLayout mChooseMenu;

    /**
     * 选择学校滚筒控件
     *
     * @param context 上下文
     */
    public WheelChooser(Context context) {
        super(context, false, true);
        init(context);
    }

    /**
     * 初始化方法
     *
     * @param context
     */
    private void init(Context context) {
        initViews(context);
        initDataAndAdatper(context);
        initEvent();
    }

    /**
     * 初化视图
     *
     * @param context
     */
    private void initViews(Context context) {
        mContext = context;
        mChooseMenu = (LinearLayout) LayoutInflater.from(mContext)
                .inflate(R.layout.widget_wheel_chooser, null);
        setContentView(mChooseMenu, true);
        setCanceledOnTouchOutside(true);
        mProvinceWV = (WheelChooserView) mChooseMenu.findViewById(R.id.year);
        mCityWV = (WheelChooserView) mChooseMenu.findViewById(R.id.month);
        mTownWV = (WheelChooserView) mChooseMenu.findViewById(R.id.day);

        int dpi = DeviceUtils.getScreenDpi();
        if (dpi >= screenDpi450) {
            defaultTextSize = size45;
        } else if (dpi >= screenDpi300) {
            defaultTextSize = size30;
        } else if (dpi >= 240) {
            defaultTextSize = 20;
        } else if (dpi <= screenDpi150) {
            defaultTextSize = size10;
        }

        mProvinceWV.setLabel("");
        mCityWV.setLabel("");
        mProvinceWV.setTextSize(defaultTextSize);
        mCityWV.setTextSize(defaultTextSize);
        mTownWV.setTextSize(defaultTextSize);
    }

    /**
     * 初始数据与适配器
     *
     * @param context
     */
    private void initDataAndAdatper(Context context) {
        mFile = ESystem.getCacheAddressFile(context);
        if (mFile.exists()) {
            mProvinceList = Utils.getCitysByType(mFile + "", 1);
            // provinceList.add(0, allCity);
            mCurProvince = mProvinceList.get(0);
        }

        int maxProvinceName = Utils.getMaxLengthOfTyep(1, mFile + "");

        boolean isPad = isPad(context);

        mProvinceAdapter = new CityChooseAdapter(mProvinceList, maxProvinceName,
                isPad);
        mProvinceWV.setAdapter(mProvinceAdapter);
        // wvProvince.setCurrentItem(calendar.get(Calendar.HOUR_OF_DAY));
        mProvinceWV.setCyclic(true);

        mCityAdapter = new CityChooseAdapter(mCityList, length, isPad);
        mCityWV.setAdapter(mCityAdapter);
        // wvCity.setCurrentItem(calendar.get(Calendar.MINUTE));
        mCityWV.setCyclic(true);
        mTownAdapter = new CityChooseAdapter(mTownList, length, isPad);
        mTownWV.setAdapter(mTownAdapter);

        mCityAdapter.setMaxinumLength(length);
        mTownAdapter.setMaxinumLength(length);
    }

    /**
     * 初始事件
     */
    private void initEvent() {
        mProvinceWV.addChangingListener(new OnWheelViewChangedListener() {

            @Override
            public void onChanged(WheelChooserView wheel, int oldValue,
                                  int value) {
                mCurProvince = mProvinceList.get(value);
                refreshData(true);
            }
        });

        mCityWV.addChangingListener(new OnWheelViewChangedListener() {
            @Override
            public void onChanged(WheelChooserView wheel, int oldValue,
                                  int value) {
                mCurCity = mCityList.get(value);
                refreshData(false);
            }
        });

        mTownWV.addChangingListener(new OnWheelViewChangedListener() {
            @Override
            public void onChanged(WheelChooserView wheel, int oldValue,
                                  int value) {
                mCurTown = mTownList.get(value);
            }
        });

        findViewById(R.id.wheel_chooser_cancel).setOnClickListener(this);
        findViewById(R.id.wheel_chooser_confirm).setOnClickListener(this);
    }

    public void setCallback(ChooseCityCallback callback) {
        this.mCallback = callback;
    }

    /**
     * 显示控件
     */
    public void showWheel() {
        showFromBottom();
    }

    /**
     * 隐藏控件
     */
    public void hideWheel() {
        dismiss();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.wheel_chooser_cancel) {
            if (mCallback != null) {
                setCurCity();
                mCallback.cancel();
            }
        } else if (v.getId() == R.id.wheel_chooser_confirm) {
            setCurCity();
            callMethod(false);
        }
    }

    /**
     * 选择城市回调
     */
    public static class ChooseCityCallback {
        /**
         * 选择城市
         *
         * @param province 省
         * @param city     市
         * @param town     镇
         */
        public void choosen(City province, City city, City town) {

        }

        /**
         * 选择城市
         *
         * @param choosenCity 城市
         * @param areaStr     String
         */
        public void choosen(City choosenCity, String areaStr) {

        }

        /**
         * 选择城市
         *
         * @param choosenCity
         * @param areaStr
         * @param province    省
         * @param city        市
         * @param town        区
         */
        public void choosen(City choosenCity, String areaStr, City province,
                            City city, City town) {

        }

        /**
         * 选择城市
         *
         * @param provinceIndex 省索引
         * @param cityIndex     市索引
         * @param townIndex     镇索引
         */
        public void choosen(int provinceIndex, int cityIndex, int townIndex) {

        }

        /**
         * 初始化回调的数据 带省市区
         *
         * @param choosenCity
         * @param areaStr
         * @param province    省
         * @param city        市
         * @param town        区
         */
        public void initCity(City choosenCity, String areaStr, City province,
                             City city, City town) {

        }

        /**
         * 初始化回调的数据
         *
         * @param choosenCity
         * @param areaStr
         */
        public void initCity(City choosenCity, String areaStr) {

        }

        /**
         * 退出
         */
        public void cancel() {
        }
    }

    /**
     * 隐藏,底部Button容器与遮层
     */
    public void hideBottomBtnAndCover() {
        findViewById(R.id.wheel_chooser_bottom_container)
                .setVisibility(View.GONE);
    }

    /**
     * 返回,地区轮菜单,用于位置操作
     *
     * @return LinearLayout
     */
    public LinearLayout getChooseMenu() {
        return mChooseMenu;
    }

    /**
     * 设置当前城市
     *
     * @param districeCoding 输入地址码，没有则输入0
     */
    public void setCurrentCity(String districeCoding) {
        setDistriceIndex(districeCoding);
        refreshData(true);
        setCurWheelChooserView();
        setCurCity();
        callMethod(true);
    }

    /**
     * 服务器地区码转换为本地数据库操作码
     *
     * @param districeCoding
     */
    private void setDistriceIndex(String districeCoding) {
        int proIndex = 0;
        int cityIndex = 0;
        int townIndex = 0;

        if (!"0".equals(districeCoding)) {
            String targetPath = ESystem.getCacheAddressFile(mContext).getAbsolutePath();

            if (mFile.exists()) {
                List<Integer> list = Utils.getAddressIndex(targetPath, districeCoding);

                int size = list.size();
                if (list != null & size > 1) {
                    if (size == 2) {
                        proIndex = list.get(0);
                        cityIndex = list.get(1);
                    } else if (size == 3) {
                        proIndex = list.get(0);
                        cityIndex = list.get(1);
                        townIndex = list.get(2);
                    }
                }
            }
        }
        this.mProvinceIndex = proIndex;
        this.mCityIndex = cityIndex;
        this.mTownIndex = townIndex;
    }

    /**
     * 设置当前地区滑轮视图
     */
    private void setCurWheelChooserView() {
        if (mProvinceIndex == -1) {
            mProvinceIndex = 0;
        }
        if (mProvinceIndex < mProvinceList.size()) {
            mProvinceWV.setCurrentItem(mProvinceIndex);
            mCurProvince = mProvinceList.get(mProvinceIndex);
        } else {
            mProvinceWV.setCurrentItem(mProvinceList.size() - 1);
            mCurProvince = mProvinceList.get(mProvinceList.size() - 1);
        }
        refreshData(true);
        if (mCityIndex != -1 && mCityList != null && mCityList.size() > 0) {
            mCityWV.setCurrentItem(mCityIndex);
            mCurCity = mCityList.get(mCityIndex);
            refreshData(false);
        }
        int mTownListSize = mTownList.size();
        if (mTownIndex != -1 && mTownList != null && mTownListSize > 0
                && mTownIndex < mTownListSize) {
            mTownWV.setCurrentItem(mTownIndex);
            mCurTown = mTownList.get(mTownIndex);
        }
    }

    /**
     * 滑动地区滑轮时刷新数据,
     *
     * @param isRefreshCity isRefreshCity为true,则刷新城市列表数据,false则只刷新城区列表数据
     */
    private void refreshData(boolean isRefreshCity) {
        if (isRefreshCity) {
            mCityList.clear();
            mCityList.addAll(Utils.getCitysByRefrence(mFile + "",
                    mCurProvince.getZoneNum()));
            if (mCityList.size() > 0) {
                mCurCity = mCityList.get(0);
                mCityWV.setCurrentItem(0);
            } else {
                mCurCity = null;
            }
            mCityWV.setAdapter(mCityAdapter);
        }
        mTownList.clear();
        if (mCurCity != null) {
            mTownList.addAll(Utils.getCitysByRefrence(mFile + "",
                    mCurCity.getZoneNum()));
            mCurTown = null;
            if (mTownList.size() > 0) {
                mCurTown = mTownList.get(0);
                mTownWV.setCurrentItem(0);
            } else {
                mCurTown = null;
            }
        }
        mTownWV.setAdapter(mTownAdapter);
    }

    /**
     * 设置当前城市数据，用于回调给客户端
     */
    private void setCurCity() {
        String str = mCurProvince.getZoneStr();

        mProvinceIndex = mProvinceList.indexOf(mCurProvince);
        mChooseCity = mCurProvince;
        if (mCurCity != null) {
            if (mCurCity.getZoneNum() != 0) {
                str += " " + mCurCity.getZoneStr();
                mChooseCity = mCurCity;
            }
            mCityIndex = mCityList.indexOf(mCurCity);
        } else {
            mCityIndex = -1;
        }
        if (mCurTown != null) {
            if (mCurTown.getZoneNum() != 0) {
                str += " " + mCurTown.getZoneStr();
                mChooseCity = mCurTown;
            }
            mTownIndex = mTownList.indexOf(mCurTown);
        } else {
            mTownIndex = -1;
        }
        // etSchoolName.setText(str);
        chooseCityStr = str;
    }

    /**
     * 回调于客户端方法,
     *
     * @param isInit isInit为true时只回调mCallback.initCity()方法,
     */
    private void callMethod(boolean isInit) {
        if (mCallback != null) {
            if (isInit) {
                mCallback.initCity(mChooseCity, chooseCityStr);
                mCallback.initCity(mChooseCity, chooseCityStr, mCurProvince,
                        mCurCity, mCurTown);
            } else {
                mCallback.choosen(mChooseCity, chooseCityStr);
                mCallback.choosen(mCurProvince, mCurCity, mCurTown);
                mCallback.choosen(mProvinceIndex, mCityIndex, mTownIndex);
                mCallback.choosen(mChooseCity, chooseCityStr, mCurProvince,
                        mCurCity, mCurTown);
            }
        }
    }

    /**
     * @param context
     * @return
     */
    private boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

}
